package com.tianhua.javs.core.service.translate;

import com.tianhua.javs.client.bean.JavsScriptMethodBean;
import com.tianhua.javs.client.bean.JavsTranslateContextBean;
import com.tianhua.javs.client.bean.ScriptVarMappingBean;
import com.tianhua.javs.core.factory.VariableFactory;
import com.tianhua.javs.core.service.translate.TranslateRouteService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Description:
 * date: 2022/2/11
 *
 * @author shenshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
public class TranslateService {


    @Autowired
    private TranslateRouteService translateRouteService;

    @Autowired
    private VariableFactory variableFactory;

    /**
     * 脚本引擎的解析入口
     * 解析单个脚本文件内容
     *
     * @param translateContextBean
     * @param className                当前脚本对应的类名
     * @param javsShellContentBeanList 按方法维度切分的脚本内容
     */
    public void exeTranslate(JavsTranslateContextBean translateContextBean, String className, List<JavsScriptMethodBean> javsShellContentBeanList) {
        if(CollectionUtils.isEmpty(javsShellContentBeanList)){
            return;
        }
        for (JavsScriptMethodBean javsScriptMethodBean : javsShellContentBeanList) {
            Map<String, List<ScriptVarMappingBean>> scriptVarMap = variableFactory.initVarPool(translateContextBean, javsScriptMethodBean);
            javsScriptMethodBean.setScriptVarMap(scriptVarMap);
            translateContextBean.setCurrentScriptMethodBean(javsScriptMethodBean);
            //对方法内的每行脚本内容进行解析
            StringBuilder javaMethodContentBuilder = new StringBuilder();
            if(CollectionUtils.isEmpty(javsScriptMethodBean.getJavsShellContentList())){
                continue;
            }
            for (String javsShellStr : javsScriptMethodBean.getJavsShellContentList()) {
                String javaResult = translateRouteService.preTranslateRoute(translateContextBean, javsShellStr);
                if(StringUtils.isEmpty(javaResult)){
                    continue;
                }
                javaMethodContentBuilder.append(javaResult + "\n");
            }
            javsScriptMethodBean.setJavaMethodContent(javaMethodContentBuilder.toString());
        }
    }
}
